package com.yonyou.pmclouds.billtype.util;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.billtype.entity.BillTypeRefVO;
import com.yonyou.pmclouds.billtype.entity.BillTypeVO;
import com.yonyou.pmclouds.billtype.rmiitf.BillTypeQuery;
import com.yonyou.pmclouds.outter.nc.NcBillTypeCustomerQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Description: 根据单据类型编码获取单据名称，先查询友工程单据，再查询NC单据
 * @Author: zhangzhonghao
 * @Date: 2020-03-06
 *
 */
@Component
public class BillTypeInfoQueryUtils {

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private BillTypeQuery billTypeQuery;

    @Autowired
    private NcBillTypeCustomerQuery ncBillTypeCustomerQuery;

    public Map<String, String> queryNameByType(String[] billTypeCodes) throws BusinessException {
        if(billTypeCodes == null || billTypeCodes.length <= 0){
            return new HashMap<>();
        }

        Map<String, String> billTypeMap = new HashMap<>();
        List<String> nccBillTypeList = new ArrayList<>();
        Map<String, BillTypeVO> billTypeVOMap = new HashMap<>();

        List<BillTypeVO> billTypeVOS = billTypeQuery.queryByCodes(billTypeCodes);
        if(billTypeVOS != null && billTypeVOS.size() > 0){
            for(BillTypeVO typeVO : billTypeVOS){
                billTypeVOMap.put(typeVO.getScode(), typeVO);
            }
        }

        for(String billType : billTypeCodes){
            BillTypeVO typeVO = billTypeVOMap.get(billType);
            if(typeVO != null){
                billTypeMap.put(billType, typeVO.getSname());
            }else {
                nccBillTypeList.add(billType);
            }
        }

        if(nccBillTypeList.size() <= 0){
            return billTypeMap;
        }

        BillTypeRefVO[] ncBillTypeRefVOs = ncBillTypeCustomerQuery.queryRelatedBillTypeForPlan();
        if(ncBillTypeRefVOs == null || ncBillTypeRefVOs.length <= 0){
            return billTypeMap;
        }

        Map<String, BillTypeRefVO> nccBillTypeMap = new HashMap<>();
        for(BillTypeRefVO billTypeRefVO : ncBillTypeRefVOs){
            nccBillTypeMap.put(billTypeRefVO.getCode(), billTypeRefVO);
        }

        for(String nccBillType : nccBillTypeList){
            BillTypeRefVO billTypeRefVO = nccBillTypeMap.get(nccBillType);
            if(billTypeRefVO != null){
                billTypeMap.put(nccBillType, billTypeRefVO.getName());
            }
        }

        return billTypeMap;
    }

}
